package accs.model.minecraft;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import accs.model.AccountChecker;
import accs.model.Context;
import accs.model.ExtendedHttpClient;
import accs.model.utils.HeaderUtils;

public class MinecraftChecker implements AccountChecker{

	public MinecraftChecker(){	
	}
	
	public MinecraftAccount login(String mail, String password, Context ctx) throws ClientProtocolException, IOException{
		DefaultHttpClient httpclient=new ExtendedHttpClient(ctx);
		
		List<NameValuePair> list= new ArrayList<NameValuePair>();
		
		HttpPost post=new HttpPost("http://login.minecraft.net/");
		post.setHeader(HeaderUtils.getUserAgent());
//		post.setHeader(HeaderUtils.getReferer(""));
		
		list.add(new BasicNameValuePair("user",mail));
		list.add(new BasicNameValuePair("password",password));
		list.add(new BasicNameValuePair("version","16"));
		post.setEntity(new UrlEncodedFormEntity(list,"UTF-8"));
		
		HttpResponse resp=httpclient.execute(post);
//		String location=resp.getFirstHeader("Location").getValue();
//		EntityUtils.consume(resp.getEntity());
//		System.out.println(EntityUtils.toString(resp.getEntity()));
//     	System.out.println("---------------------------------------------------------------");
		
		BufferedReader br=new BufferedReader(new InputStreamReader(resp.getEntity().getContent(),"utf-8"));
		String line=null;
		
		boolean valid = false;
		String mig = "";
		
		while((line=br.readLine())!= null){
			line=line.trim();
			System.out.println(line);
			
			if(line.contains("Account migrated")){
				mig = line;
			}
			if(line.contains(":deprecated:")){
				valid = true;
			}
			
		}
		
		if(valid){
			MinecraftAccount ma = new MinecraftAccount(mail, password, mig);
			return ma;
		}else{
			return null;
		}
		
	}

	public String getName() {
		return "minecraft";
	}

	public URL getImage() {
		return MinecraftChecker.class.getResource("/accs/gui/img/minecraft.png");
	}
}